package com.memory.wechat.controller;

import com.memory.wechat.domain.msg.MessageType;
import com.memory.wechat.domain.service.WeChatService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Map;

/**
 * 微信接受消息校验控制器
 */
@RestController
public class WxMainController {
    private static final String TOKEN = "zckj";

    @Resource
    private WeChatService weChatService;

    @RequestMapping(value = "/wechat",produces = "text/html;charset=utf-8")
    public void wechat(HttpServletResponse response, HttpServletRequest request) throws Exception{
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        //排序
        String[] arr = {TOKEN, timestamp, nonce};
        Arrays.sort(arr);

        StringBuilder content = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            content.append(arr[i]);
        }

        //sha1Hex 加密
        MessageDigest md = null;
        String temp = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(content.toString().getBytes());
            temp = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        if ((temp.toLowerCase()).equals(signature)){
            //验证通过
            System.out.println(">>>>>验证通过");
            if(!StringUtils.isEmpty(echostr)) {
                response.getWriter().write(echostr);
            }else {
                try {
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("text/xml");
                    //调用parseXml方法解析请求消息
                    Map<String, String> map = MessageType.parseXml(request, response);
                    String MsgType = map.get("MsgType");
                    System.out.println(">>>>消息类型："+MsgType);
                    String xml = null;//处理输入消息，返回结果的xml
                    if(MessageType.REQ_MESSAGE_TYPE_EVENT.equals(MsgType)){
                        xml = weChatService.parseEvent(map);
                    }else{
                        xml = weChatService.parseMessage(map);
                    }
                    //返回封装的xml
                    if(StringUtils.isEmpty(xml)){
                        response.getWriter().write("");
                    }else {
                        response.getWriter().write(xml);
                    }

                } catch (Exception ex) {
                    ex.printStackTrace();
                    response.getWriter().write("");
                }
            }

        }else {
            System.out.println(">>>>>验证不通过");
        }
    }

    private static String byteToStr(byte[] byteArray){
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    private static String byteToHexStr(byte mByte){
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A','B', 'C', 'D', 'E', 'F' };
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4)& 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];
        String s = new String(tempArr);
        return s;
    }

}
